import React, {Component} from 'react';
import {  Modal,  Form,  Input,  Select,  DatePicker,  Popconfirm
    ,  Row,  Col,  Button,  Icon, Checkbox, Upload,  message,Table,Pagination} from 'antd';
import { routerRedux } from 'dva/router';
import styles from './main.less';
import * as  ContractModel from '../model/contract';
import * as  CustomerModel from '../model/customer';
import * as  ProductModel from '../model/product';
import _ from 'underscore'
import EditProduct from './component/edit_purchase_product'
import AddPurchase from './component/add_purchase'
import moment from 'moment'
const config = require('../config.js');

class _Main extends Component {

  constructor(props) {
    super(props);
    this.state = {page:1,pageSize:10,orderBy:'createAt',filter:{},data:{list:[]}};
    this.updateList()
  }
  async updateList(nstate={}){
      nstate = Object.assign({},this.state,nstate) //全备份
      nstate.filter = Object.assign({},this.state.filter,nstate.filter||{})
      let filter = Object.assign(this.state.filter,nstate.filter||{})
      for(let k of Object.keys(nstate.filter)){
          if(filter[k]==''|| filter[k]=='全部'){
              delete nstate.filter[k];
          }
      }
      var res = await  ContractModel.fetch({
          filter:nstate.filter,
          orderBy:nstate.orderBy,
          startPos:nstate.pageSize*(nstate.page-1),
          limit:10
      })
      if(res.status == 'success'){
        let _Map
        let contractlist = res.data.list
        let res2 = await CustomerModel.fetch({filter:{cnum:{$in:contractlist.map(d=>d.customer_num)}},limit:1000})
        _Map = _.object(res2.data.list.map(d=>d.cnum),res2.data.list)
        contractlist.map(d=>d.customer=_Map[d.customer_num]||{})
        nstate.data = res.data;

        let res3 = await ProductModel.fetch({filter:{cnum:{$in:_.flatten(contractlist.map(d=>d.products.map(d2=>d2.product_num)))}},limit:1000})
        _Map = _.object(res3.data.list.map(d=>d.cnum),res3.data.list)
        contractlist.map(ct=>{
          ct.products.map(pd=>{
            let item =_Map[pd.product_num]||{}
            _.pairs(item).map((kv)=>{
              let [k,v] = kv
              pd[k] = v
            })
          })
        })

        this.setState(nstate)
      }else{
          message.error('查询失败')
      }
  }
  async updateProductList(contract_num,products){
    console.log('updateProductList',{products})
    let res = await ContractModel.updateByNum(contract_num,{products})
    this.updateList({})
  }
  updateCheck(contract_num,product_num,e){
    console.log('updateCheck',contract_num,product_num,e.target.checked)
    this.state.data.list.filter(d=>d.cnum===contract_num).map(d=>{
      d.products.filter(d2=>d2.product_num===product_num).map(pd=>{
        console.log('setted')
        pd.checked = e.target.checked
      })
    })
    this.setState({data:this.state.data})
  }
  render() {
    console.log("render state",this.state);
      const columns = [
        {
          title: '基本信息',
          dataIndex: 'offline_num',
          key: 'offline_num',
          render: (text,record) => (<div>
              <div>编号: {record.cnum}</div>
              <div>线下合同号: {record.offline_num}</div>
              <div>城市: {record.customer.city_num}</div>
              <div>客户编号: {record.customer.cnum}</div>
              <div>客户姓名: {record.customer.name}</div>
              <div>客户详细地址: {record.customer.address}</div>
              <div>计划到货日期: {record.plan_arrive_at==''?'': moment(record.plan_arrive_at).format('YYYY-MM-DD')}</div>
              </div>)
        },
        {
          title: '商品信息',
          dataIndex: 'cnum',
          key: 'cnum',
          render: (text,record) => (<div>
            {record.products.map(pd=>
              <div key={pd.product_num}>
                <div>原价：{pd.origin_money}</div>
                <div>折扣：{pd.discount}</div>
                <div>合同售价：{pd.contract_money}</div>
                <div>产品编号：{pd.cnum}</div>
                <div>品牌：{pd.brand_num}</div>
                <div>产品名字：{pd.name}</div>
                <div>产品型号：{pd.model}</div>
                <div>数量：{pd.quantity}</div>
                <div>图片: <img style={{width:"50px",heigth:"50px"}} src={config.host+'/file/'+pd.pic}/></div>
                {pd.status === 'purchased'?
                    <div style={{color:"green"}}>已下单 {pd.stocks?pd.stocks.map(st=><span key={st.stock_num}> , {st.stock_num}</span>):' some wrong'}
                    </div>
                  :
                    <div style={{color:"red"}}>
                      待下单
                      <Checkbox checked={pd.checked===true} onChange={v=>this.updateCheck(record.cnum,pd.product_num,v)}/>
                    </div>
                }
                <div style={{color:pd.status === 'puarchased'?'green':'red'}}>状态：{pd.status === 'puarchased' ?'':'' }</div>
              </div>
            )
          }
              </div>)
        },
        {
          title: '操作',
          dataIndex: '_id',
          key: '_id',
          render: (text,record) => (<div>
            <EditProduct record={record} updateProductList={(list)=>this.updateProductList(record.cnum,list)}>
              <Button type="info">编辑商品</Button></EditProduct>
            <AddPurchase record={record} count={record.products.filter(d=>d.checked===true).length} products={record.products.filter(d=>d.checked===true)} updateList={()=>this.updateList()}>
                <Button type="danger">生成采购单({record.products.filter(d=>d.checked===true).length})</Button></AddPurchase>
          </div>)
        }

      ];

    return (
      <div>
            <Row>
              <Col span={12}>销售合同列表</Col>
              <Col span={12}>
                  <Row type="flex" justify="end">
                  </Row>
              </Col>
            </Row>
            <Table columns={columns} dataSource={this.state.data.list}
                rowKey={record => record.cnum} pagination={false} scroll={{ x: 1000}}/>
            <Pagination className="ant-table-pagination"
              total={this.state.data.count} current={this.state.page} pageSize={this.state.pageSize} showSizeChanger
              showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`}
              onChange={(page, pageSize)=>{this.updateList({page:page})}}
              onShowSizeChange={(current, size)=>this.updateList({pageSize:size})}/>
      </div>
    );
  }


}


export default _Main;
